package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/asaskevich/govalidator"
	"strconv"
	"publish/app/account/model"
	"time"
	"github.com/astaxie/beego"
)

func AddAutoTask(ctx *gin.Context) Result{

	autoTaskVO := &model.AutoTask{}
	if err := ctx.BindJSON(autoTaskVO);err != nil{
		return BindErrorResult
	}
	autoTaskVO.CreateTime = time.Now()
	err := model.AddAutoTask(autoTaskVO)
	if err != nil{
		return ErrorResult(err)
	}

	return SuccessResult
}


func UpdateAutoTask(ctx *gin.Context) Result{

	autoTaskVO := &model.AutoTask{}
	if err := ctx.BindJSON(autoTaskVO);err != nil{
		return BindErrorResult
	}

	if _,err := govalidator.ValidateStruct(autoTaskVO);err != nil{
		return ValidErrorResult
	}

	err := model.UpdateAutoTask(autoTaskVO)
	if err != nil{
		return ErrorResult(err)
	}

	return SuccessResult
}

func GetAutoTaskById(ctx *gin.Context) Result{

	idQ := ctx.Query("id")
	id,_ := strconv.Atoi(idQ)
	if id <= 0 {
		return ValidErrorResult
	}

	nAutoTask,err := model.GetAutoTaskById(id)
	if err != nil{
		return ErrorResult(err)
	}

	return DataResult(nAutoTask)
}

func DeleteAutoTask(ctx *gin.Context) Result{

	idReq := &IdReq{}
	if err := ctx.BindJSON(idReq);err != nil{
		return BindErrorResult
	}

	if _,err := govalidator.ValidateStruct(idReq);err != nil{
		return ValidErrorResult
	}

	err := model.DeleteAutoTask(idReq.Id)
	if err != nil{
		return ErrorResult(err)
	}

	return SuccessResult
}


func ListAutoTask(ctx *gin.Context) Result{
	autoTasks,err := model.ListAutoTask()
	if err != nil {
		return ErrorResult(err)
	}

	return DataResult(autoTasks)
}

func ListAutoTaskByPage(ctx *gin.Context) Result{

	pageQ := ctx.DefaultQuery("page","1")
	sizeQ := ctx.DefaultQuery("size","10")
	page,_ := strconv.Atoi(pageQ)
	size,_ := strconv.Atoi(sizeQ)

	result,count,err := model.ListAutoTaskByPage(page,size)
	if err != nil{
		return ErrorResult(err)
	}

	for i,pub := range result {
		account, err := model.GetAccountById(pub.AccountId)
		if err != nil {
			beego.Error(err)
			return ErrorResult(err)
		}

		result[i].Account = account
	}

	return DataResult(model.Page{Page:page,PageSize:size,Count:count,Data:result})
}

